package com.taotao.netty.protobuf.server;

import com.taotao.netty.protobuf.MyMutiDataInfo;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;

/**
 * @Description:
 * @Author: TaoJF
 * @Date: Created in 2018/6/30 下午9:02
 */
public class ProtobufServerInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        // 用于对Probuf类型序列化；
        pipeline.addLast(new ProtobufEncoder());
        // 反序列化指定的Probuf字节数组为protobuf类型;
        pipeline.addLast(new ProtobufDecoder(MyMutiDataInfo.MyMessage.getDefaultInstance()));
        // 用于decode前解决半包和粘包问题（利用包头中的包含数组长度来识别半包粘包）;
        pipeline.addLast(new ProtobufVarint32FrameDecoder());
        // 用于在序列化的字节数组前加上一个简单的包头，只包含序列化的字节长度;
        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());

        pipeline.addLast(new ProtobufServerHandler());
    }
}
